var handytab = {
  onLoad: function() {
    // initialization code
    this.initialized = true;
    this.strings = document.getElementById("handytab-strings");
  },

  showTab: function() {
    var attrName = "handytab";
    var url = "chrome://handytab/locale/handytab.html";

    var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                       .getService(Components.interfaces.nsIWindowMediator);
    for (var found = false, index = 0, tabbrowser = wm.getEnumerator('navigator:browser').getNext().gBrowser;
         index < tabbrowser.tabContainer.childNodes.length && !found;
         index++) {

      // Get the next tab
      var currentTab = tabbrowser.tabContainer.childNodes[index];
    
      // Does this tab contain our custom attribute?
      if (currentTab.hasAttribute(attrName)) {

        // Yes--select and focus it.
        tabbrowser.selectedTab = currentTab;

        // Focus *this* browser window in case another one is currently focused
        tabbrowser.ownerDocument.defaultView.focus();
        found = true;
      }
    }

    if (!found) {
      // Our tab isn't open. Open it now.
      var browserEnumerator = wm.getEnumerator("navigator:browser");
      var tabbrowser = browserEnumerator.getNext().gBrowser;
    
      // Create tab
      var newTab = tabbrowser.addTab(url);
      newTab.setAttribute(attrName, "true");
      newTab.setAttribute("flex", 0);
      newTab.setAttribute("minwidth", 0);
    
      // Focus tab
      tabbrowser.selectedTab = newTab;
      
      // Focus *this* browser window in case another one is currently focused
      tabbrowser.ownerDocument.defaultView.focus();
    }
  }
};

window.addEventListener("load", handytab.onLoad, false);
